package com.sk.skplanet.commute.actions;

import java.util.ArrayList;
import java.util.Collections;

import android.content.Context;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sk.skplanet.commute.R;
import com.sk.skplanet.commute.vo.Data;
import com.sk.skplanet.commute.vo.Point;
import com.sk.skplanet.commute.vo.Route;

public class API_cennectingThread extends Thread {
	LinearLayout layout_pointlist;
	Context context;
	Route route;
	TextView[] textViewArr = new TextView[5];
	boolean api_connectingThread_run;
	SortingHandler sortingHandler;

	public API_cennectingThread(Context context, LinearLayout layout_pointlist, Route route,
			boolean api_connectingThread_run, SortingHandler sortingHandler) {
		this.layout_pointlist = layout_pointlist;
		this.context = context;
		this.route = route;
		this.api_connectingThread_run = api_connectingThread_run;
		this.sortingHandler = sortingHandler;

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (api_connectingThread_run) {
			try {
				Thread.sleep(Data.THREAD_INTERVALTIME);

				if (route.getPoints() != null) {
					for (int pointPosition = 0; pointPosition < route.getPoints().size(); pointPosition++) {
						Point point = route.getPoints().get(pointPosition);
						LinearLayout layout_point = (LinearLayout) layout_pointlist.getChildAt(pointPosition);
						ArrayList<LinearLayout> tvArr = new ArrayList<LinearLayout>();
						if (point.getStopInfos() != null) {
							for (int stopinfoPosition = 0; stopinfoPosition < point.getStopInfos().size(); stopinfoPosition++) {
								LinearLayout layout_stopinfo = (LinearLayout) layout_point
										.getChildAt(stopinfoPosition + 1);
								if (layout_stopinfo != null) {
									textViewArr[0] = (TextView) layout_stopinfo.findViewById(R.id.textview_busNum);
									textViewArr[1] = (TextView) layout_stopinfo.findViewById(R.id.textview_arrivaltime);
									textViewArr[2] = (TextView) layout_stopinfo.findViewById(R.id.textview_starttime);
									textViewArr[3] = (TextView) layout_stopinfo.findViewById(R.id.textview_lasttime);
									textViewArr[4] = (TextView) layout_stopinfo.findViewById(R.id.textview_arrivalstop);

									if (textViewArr[1].getTag() != null) tvArr.add(layout_stopinfo); // sorting

									Log.i("thread", "(point:" + pointPosition + ",sopinfo:" + stopinfoPosition + ")");
								}
							}
						}
						Collections.sort(tvArr, new comp());

						sortingHandler.setParameters(layout_point, point, tvArr);
						sortingHandler.sendEmptyMessage(0);
					}

				}

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

				Log.i("thread", "died");
				return;
			}

		}
	}

}
